package Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This servlet updates a player's accumulated score and save the user's current level progress ono the database.
 * @author Rodge Uy
 */
@PersistenceContext(name = "persistence/LogicalName", unitName = "GooWherePU")
public class PlayerUpdateServlet extends HttpServlet {

    @Resource
    private javax.transaction.UserTransaction utx;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //request.setAttribute("loginInfo", setRegister(request.getParameter("userName"),request.getParameter("email"),request.getParameter("passWord")));
        if (request.getParameter("userName") != null && request.getParameter("curLevel") != null && request.getParameter("curScore") != null) {
            setUpdate(request.getParameter("userName"), request.getParameter("curLevel"), request.getParameter("curScore"));
        } else if (request.getParameter("userName") != null && request.getParameter("newEmail")!=null && request.getParameter("newPassword")!=null) {
            int success = updateUserInfo(request.getParameter("userName"),request.getParameter("newEmail"),request.getParameter("newPassword"));
            PrintWriter out = response.getWriter();
            out.print(success);
        }


    }

    private void setUpdate(String userName, String curLevelStr, String curScoreStr) {

        //convert strings to integers
        int curLevel = Integer.parseInt(curLevelStr);
        int curScore = Integer.parseInt(curScoreStr);


        try {

            Context ctx = GetContext.getContext();
            utx.begin();

            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            //create Query that finds the Player by username and updates the accumScore and furthestPlayedLevel variables
            Query q = em.createNamedQuery("Player.updateLevelAndScore").setParameter("playName", userName).setParameter("accumScore", curScore).setParameter("furthestPlayedLevel", curLevel);

            int updated = q.executeUpdate();
            System.out.println(updated);

            utx.commit();


        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);

        }
        return;
    }

        private int updateUserInfo(String userName, String newEmail, String newPassword) {
        try {

            Context ctx = GetContext.getContext();
            utx.begin();

            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            //try to find the username in the database first
            Query q = em.createNamedQuery("Player.updateUserInfo").setParameter("playName", userName).setParameter("email", newEmail).setParameter("password", newPassword);

            int updated = q.executeUpdate();

            utx.commit();

            return updated;
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
            return -1;
        }
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    protected void persist(Object object) {
        try {
            Context ctx = GetContext.getContext();
            utx.begin();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            em.persist(object);
            utx.commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }
}
